#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <string.h>
#include "buffer.h"

#define BUFFER_SIZE 1<<6
#define MESSAGE_SIZE 1<<7

struct s_buffer* buffer_init (int fd){
	
	struct s_buffer* buffer = malloc (sizeof(struct s_buffer));
	buffer->messages = malloc(BUFFER_SIZE*(sizeof(char*)));
	buffer->fd = fd;
	buffer->count = 0;
	return buffer;

}

void buffer_flush(struct s_buffer* buffer){

	int i = 0;
	for (i = 0; i < buffer->count; ++i){
		write(buffer->fd, buffer->messages[i], strlen(buffer->messages[i]));
		write(buffer->fd, "\n", 1);
	}
	buffer->count = 0;
}

void buffer_write(struct s_buffer* buffer,char* message,int length){

	if (buffer->count == BUFFER_SIZE)
		buffer_flush(buffer);

	if (length < MESSAGE_SIZE){
		buffer->messages[buffer->count++] = message;
	}else{
		printf("LOGGER: MESSAGE - %s\nIS TOO LONG\n",message);
	}
}

void buffer_finish (struct s_buffer* buffer){

	buffer_flush(buffer);
	free(buffer->messages);
	free(buffer);
}

/*int main(int argc, char* argv[]){

	char message[100] = "123";
	int fd = open ("output.txt", O_RDWR | O_CREAT | O_TRUNC,0666);
	struct s_buffer* buffer = buffer_init(fd);
	buffer_write(buffer,message,100);
	buffer_write(buffer,message,100);

	buffer_finish(buffer);
	return 0;
}
*/